package org.texteasy.sms;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

import org.texteasy.BulkMessenger;
import org.texteasy.R;
import org.texteasy.TextEasyApp;
import org.texteasy.sms.RecipientCache.UpdateListener;
import org.texteasy.sms.SMSConstants.ThreadsColumns;

import android.app.ListActivity;
import android.content.ContentUris;
import android.content.Context;
import android.content.Intent;
import android.database.CharArrayBuffer;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.provider.ContactsContract.Contacts;
import android.text.format.DateUtils;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.ResourceCursorAdapter;
import android.widget.TextView;

public class SMSConversationsList extends ListActivity implements UpdateListener{

	private static final int FROM_COLUMN_INDEX = 3;
	private static final int SUBJECT_COLUMN_INDEX = 4;
	private static final int DATE_COLUMN_INDEX = 1;
	private static final int THREAD_ID_COLUMN_INDEX = 0;
	
	private Handler handler;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		
		setContentView(R.layout.sms_history_list);
		
		ListView listView = getListView();
		listView.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
		
		TextEasyApp application = (TextEasyApp)getApplication();
		
		Cursor cursor = getContentResolver().query(
				SMSConstants.allThreadsUri, SMSConstants.smsHistoryProjection, 
				ThreadsColumns.DATE + " <= ?", new String[]{ Long.toString(
					application.getRecipientCache().getQueryDate())}, 
				SMSConstants.DEFAULT_SORT_ORDER);
		
		setListAdapter(new SMSItemListAdapter(this, R.layout.sms_history_row, cursor));
		handler = new Handler();
	}
	
	@Override
	protected void onResume() {
		super.onResume();
		
		TextEasyApp application = (TextEasyApp)getApplication();
		application.getRecipientCache().addListener(this);
	}
	
	@Override
	protected void onPause() {
		super.onPause();
		
		TextEasyApp application = (TextEasyApp)getApplication();
		application.getRecipientCache().removeListener(this);
	}
	
	@Override
	protected void onListItemClick(ListView l, View v, int position, long id) {
		super.onListItemClick(l, v, position, id);
		
		Cursor cursor = (Cursor) getListView().getItemAtPosition(position);
		
		long threadId = cursor.getLong(THREAD_ID_COLUMN_INDEX);
		Intent intent = new Intent(this, SMSThreadList.class);
		intent.putExtra(SMSThreadList.EXTRA_THREAD_ID, threadId);
		//only one action pick sms so hard coding it to 0
		startActivityForResult(intent, 0);
	}
	
	@Override
	public void onRecipientCacheUpdated() {
		
		handler.post(new Runnable(){
			@Override
			public void run() {
				((ResourceCursorAdapter)getListAdapter()).notifyDataSetChanged();
			}
		});
		
	}
	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		
		if(resultCode != RESULT_CANCELED && requestCode == 0){
			setResult(RESULT_OK, data);
			finish();
		}
		
	}
	
	final static class SMSListItemCache {
		public TextView recipientIdView;
		public TextView dateView;
		public TextView subjectView;
		public ImageView avatarView;
		
	}

	
	private static final class SMSItemListAdapter extends ResourceCursorAdapter {
		
		private final int dateFormatFlags; 
		private final CharSequence unknownNameText;
		private final RecipientCache recipientCache;
		private final Drawable sDefaultContactImage;
		private final SMSConversationsList parent; 
		
		private int firstVisiblePosition;
		private int lastVisibilePosition;
		
		public SMSItemListAdapter(final Context context,final int resource,
				final Cursor cursor) {
			super(context, resource, cursor);
			
			dateFormatFlags = DateUtils.FORMAT_NO_NOON_MIDNIGHT |
            	DateUtils.FORMAT_ABBREV_ALL | DateUtils.FORMAT_CAP_AMPM |
            	DateUtils.FORMAT_SHOW_YEAR | DateUtils.FORMAT_SHOW_DATE;
			unknownNameText = context.getText(android.R.string.unknownName);
			
			SMSConversationsList conversationList = (SMSConversationsList)context;
			TextEasyApp application = (TextEasyApp)conversationList.getApplication();
			recipientCache = application.getRecipientCache();
			
			sDefaultContactImage = context.getResources().getDrawable(R.drawable.ic_contact_picture);
			
			parent = (SMSConversationsList)context;
		}
		
		@Override
		public View newView(final Context context,final  Cursor cursor,final ViewGroup parent) {
			final View view = super.newView(context, cursor, parent);
			
			final SMSListItemCache cache = new SMSListItemCache();
			cache.recipientIdView = (TextView)view.findViewById(R.id.sms_conversation_from);
			cache.dateView = (TextView)view.findViewById(R.id.sms_conversation_date);
			cache.subjectView = (TextView)view.findViewById(R.id.sms_conversation_subject);
			cache.avatarView = (ImageView)view.findViewById(R.id.avatar);
			view.setTag(cache);
			return view;
		}
		
		@Override
		public void bindView(final View view,final Context context,final Cursor cursor) {
			
			firstVisiblePosition = parent.getListView().getFirstVisiblePosition();
			lastVisibilePosition = parent.getListView().getLastVisiblePosition();
			
			Log.e(getClass().getSimpleName(), "firstVisiblePosition: " + firstVisiblePosition + 
					" lastVisibilePosition: " + lastVisibilePosition);
			
			final SMSListItemCache cache = (SMSListItemCache) view.getTag();
			
			String recipientIds = cursor.getString(FROM_COLUMN_INDEX);
			
			ArrayList<Contact> contacts = recipientCache.getContactsByRecipientIds(
					recipientIds.split(" "));
			
			StringBuilder recipientIdsBuilder = new StringBuilder();
			for(Contact contact: contacts){
				recipientIdsBuilder.append(contact.getDisplayValue()).append(" ");
			}
			
			
			if(recipientIdsBuilder.toString().trim() != ""){
				cache.recipientIdView.setText(recipientIdsBuilder.toString());
			}else{
				cache.recipientIdView.setText(unknownNameText);
			}
			
			long date = cursor.getLong(DATE_COLUMN_INDEX);
			cache.dateView.setText(DateUtils.formatDateTime(context, 
				date, dateFormatFlags));
			
			String subject = cursor.getString(SUBJECT_COLUMN_INDEX);
			if(!"".equals(subject.trim())){
				cache.subjectView.setText(subject);
			}else{
				cache.subjectView.setText(unknownNameText);
			}
			
			
			if(contacts.size() == 1 && contacts.get(0).getAvatar() != null){
				cache.avatarView.setImageDrawable(contacts.get(0).getAvatar());
			}else{
				cache.avatarView.setImageDrawable(sDefaultContactImage);
			}
			//cache.avatarView.setScaleType(ImageView.ScaleType.CENTER_INSIDE);
		}
		
		
		
		
	}
	
}
